package com.zhaiweijia.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.zhaiweijia.bean.Article;
import com.zhaiweijia.bean.User;
import com.zhaiweijia.service.ArticleService;
import com.zhaiweijia.service.UserService;

@Controller
@RequestMapping("admin")
public class AdminController {
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 跳转到管理员中心首页
	 * @return
	 */
	@RequestMapping({"/","","index"})
	public String index() {
		
		
		return "admin/index";
	}

	/**
	 * 所有文章展示
	 * @param m
	 * @param article
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("articles")
	public String articles(Model m,Article article,
			@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "5") Integer pageSize) {
		
		//如果status的值是2
		if(article.getStatus() != null && article.getStatus()==2) {
			article.setStatus(null);
		}
			
		
		//查询数据
		PageInfo<Article> info = articleService.list(pageNum, pageSize, article);
		
		m.addAttribute("info", info);
		m.addAttribute("article", article);
		
		return "admin/articles";
	}
	
	/**
	 * 修改文章状态
	 * @param article
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public boolean update(Article article) {
		
		//设置修改时间
		article.setUpdated(new Date());
		
		return articleService.update(article);
	}
	
	/**
	 * 用户管理
	 * @param m
	 * @param user
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("users")
	public String users(Model m,User user,
			@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "5") Integer pageSize) {
		
		//如果locked的值是2
		if(user.getLocked() != null && user.getLocked()==2) {
			user.setLocked(null);
		}
		
		//查询数据
		PageInfo<User> info = userService.list(pageNum, pageSize, user);
		
		m.addAttribute("info", info);
		m.addAttribute("user", user);
		
		return "admin/users";
	}
	
	/**
	 * 修改用户的锁定状态
	 * @param user
	 * @return
	 */
	@RequestMapping("updateLocked")
	@ResponseBody
	public boolean updateLocked(User user) {
		
		//设置修改时间
		user.setUpdated(new Date());
		
		return userService.updateLocked(user);
	}
}
